package com.macro.mall.portal.service.impl;

import com.macro.mall.mgb.model.CartItem;
import com.macro.mall.mgb.model.ProductFullReduction;
import com.macro.mall.mgb.model.ProductLadder;
import com.macro.mall.mgb.model.SkuStock;
import com.macro.mall.portal.dao.PortalProductDao;
import com.macro.mall.portal.domain.CartPromotionItem;
import com.macro.mall.portal.domain.PromotionProduct;
import com.macro.mall.portal.service.OmsPromotionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wangwang
 * @version 1.0
 * @description 计算促销服务
 * @date 2025/8/2 14:44
 */
@Service
public class OmsPromotionServiceImpl implements OmsPromotionService {
    @Autowired
    private PortalProductDao portalProductDao;


    @Override
    public List<CartPromotionItem> calcCartPromotion(List<CartItem> cartItemList) {
        //1.先根据productId对CartItem进行分组，以spu为单位进行计算优惠
        Map<Long, List<CartItem>> productCartMap = groupCartItemBySpu(cartItemList);
        //2.查询所有商品的优惠相关信息
        List<PromotionProduct> promotionProductList = getPromotionProductList(cartItemList);
        //3.根据商品促销类型计算商品促销优惠价格
        ArrayList<CartPromotionItem> cartPromotionItemList = new ArrayList<>();
        for (Map.Entry<Long, List<CartItem>> entry : productCartMap.entrySet()) {
            Long productId = entry.getKey();
            List<CartItem> itemList = entry.getValue();
            //3.1根据商品id查找促销信息
            PromotionProduct promotionProduct = getPromotionProductById(productId, promotionProductList);
            //3.2获取促销类型
            Integer promotionType = promotionProduct.getPromotionType();
            //促销类型：0->没有促销使用原价;1->使用促销价；2->使用会员价；3->使用阶梯价格；4->使用满减价格；5->限时购
            if (promotionType == 1) {
                for (CartItem cartItem : itemList) {
                    CartPromotionItem cartPromotionItem = new CartPromotionItem();
                    BeanUtils.copyProperties(cartItem, cartPromotionItem);
                    cartPromotionItem.setPromotionMessage("单品促销");

                    SkuStock skuStock = getOriginalPrice(promotionProduct, cartItem.getProductSkuId());
                    BigDecimal originalPrice = skuStock.getPrice();
                    //减去的金额
                    cartPromotionItem.setPrice(originalPrice);
                    cartPromotionItem.setReduceAmount(originalPrice.subtract(skuStock.getPromotionPrice()));
                    cartPromotionItem.setRealStock(skuStock.getStock() - skuStock.getLowStock());
                    cartPromotionItem.setIntegration(promotionProduct.getGiftPoint());
                    cartPromotionItem.setIntegration(promotionProduct.getGiftGrowth());
                    cartPromotionItemList.add(cartPromotionItem);
                }
                //使用阶梯价格
            } else if (promotionType == 3) {
                int count = getCartItemCount(itemList);
                ProductLadder productLadder = getProductLadder(count,promotionProduct);
                if(productLadder != null){
                    for (CartItem cartItem : itemList) {
                        CartPromotionItem cartPromotionItem = new CartPromotionItem();
                        BeanUtils.copyProperties(cartItem, cartPromotionItem);
                        cartPromotionItem.setPromotionMessage(getLadderPromotionMessage(productLadder));

                        //商品原价-折扣*商品原价
                        SkuStock skuStock = getOriginalPrice(promotionProduct,cartItem.getProductSkuId());
                        BigDecimal originalPrice = skuStock.getPrice();

                        BigDecimal reduceAmount = originalPrice.subtract(productLadder.getDiscount().multiply(originalPrice));
                        cartPromotionItem.setReduceAmount(reduceAmount);
                        cartPromotionItem.setRealStock(skuStock.getStock()-skuStock.getLockStock());
                        cartPromotionItem.setIntegration(promotionProduct.getGiftPoint());
                        cartPromotionItem.setGrowth(promotionProduct.getGiftGrowth());
                        cartPromotionItemList.add(cartPromotionItem);
                    }
                }
                else {
                    handleNoReduce(cartPromotionItemList,itemList,promotionProduct);
                }
            } else if (promotionType == 4) {
                BigDecimal totalAmount = getCartItemAmount(itemList,promotionProductList);
                ProductFullReduction fullReduction = getProductFullReduction(totalAmount, promotionProduct.getProductFullReductionList());
                if(fullReduction!=null){
                    for (CartItem item : itemList) {
                        CartPromotionItem cartPromotionItem = new CartPromotionItem();
                        BeanUtils.copyProperties(item,cartPromotionItem);
                        String message = getFullReductionPromotionMessage(fullReduction);
                        cartPromotionItem.setPromotionMessage(message);
                        //(商品原价/总价)*满减金额
                        SkuStock skuStock= getOriginalPrice(promotionProduct, item.getProductSkuId());
                        BigDecimal originalPrice = skuStock.getPrice();
                        BigDecimal reduceAmount = originalPrice.divide(totalAmount, RoundingMode.HALF_EVEN).multiply(fullReduction.getReducePrice());
                        cartPromotionItem.setReduceAmount(reduceAmount);
                        cartPromotionItem.setRealStock(skuStock.getStock()-skuStock.getLockStock());
                        cartPromotionItem.setIntegration(promotionProduct.getGiftPoint());
                        cartPromotionItem.setGrowth(promotionProduct.getGiftGrowth());
                        cartPromotionItemList.add(cartPromotionItem);
                    }
                }else{
                    handleNoReduce(cartPromotionItemList,itemList,promotionProduct);
                }
            } else {
                handleNoReduce(cartPromotionItemList,itemList,promotionProduct);
            }
        }
        return cartPromotionItemList;
    }



    /**
     * 获取购物车中指定商品的总价
     */
    private BigDecimal getCartItemAmount(List<CartItem> itemList, List<PromotionProduct> promotionProductList) {
        BigDecimal amount = new BigDecimal(0);
        for (CartItem item : itemList) {
            //计算出商品原价
            PromotionProduct promotionProduct = getPromotionProductById(item.getProductId(), promotionProductList);
            SkuStock skuStock = getOriginalPrice(promotionProduct,item.getProductSkuId());
            amount = amount.add(skuStock.getPrice().multiply(new BigDecimal(item.getQuantity())));
        }
        return amount;
    }

    private ProductLadder getProductLadder(int count, PromotionProduct promotionProduct) {
        List<ProductLadder> productLadderList = promotionProduct.getProductLadderList();
        productLadderList.sort((o1, o2) -> o2.getCount() - o1.getCount());
        for (ProductLadder productLadder : productLadderList) {
            if(count >= productLadder.getCount()){
                return productLadder;
            }
        }
        return null;
    }

    private ProductFullReduction getProductFullReduction(BigDecimal totalAmount, List<ProductFullReduction> fullReductionList) {
        //按条件从高到低排序
        fullReductionList.sort((o1, o2) -> o2.getFullPrice().subtract(o1.getFullPrice()).intValue());
        for(ProductFullReduction fullReduction:fullReductionList){
            if(totalAmount.subtract(fullReduction.getFullPrice()).intValue()>=0){
                return fullReduction;
            }
        }
        return null;
    }

    /*
        以spu为单位对购物车中商品进行分组
     */
    private Map<Long, List<CartItem>> groupCartItemBySpu(List<CartItem> cartItemList) {
        TreeMap<Long, List<CartItem>> cartItemTreeMap = new TreeMap<>();
        for (CartItem item : cartItemList) {
            List<CartItem> itemList = cartItemTreeMap.get(item.getProductId());
            if (itemList == null) {
                ArrayList<CartItem> cartItems = new ArrayList<>();
                cartItems.add(item);
                cartItemTreeMap.put(item.getProductId(), cartItems);
            } else {
                itemList.add(item);
            }
        }
        return cartItemTreeMap;
    }

    /**
     * 查询所有商品的优惠相关信息
     */
    private List<PromotionProduct> getPromotionProductList(List<CartItem> cartItemList) {
        List<Long> ids = cartItemList.stream().map(CartItem::getProductId).collect(Collectors.toList());
        return portalProductDao.getPromotionProductList(ids);
    }

    /**
     * 根据商品id获取商品的促销信息
     */
    private PromotionProduct getPromotionProductById(Long productId, List<PromotionProduct> promotionProductList) {
        for (PromotionProduct promotionProduct : promotionProductList) {
            if (productId.equals(promotionProduct.getId())) {
                return promotionProduct;
            }
        }
        return null;
    }

    /**
     * 获取商品的原价
     */
    private SkuStock getOriginalPrice(PromotionProduct promotionProduct, Long productSkuId) {
        for (SkuStock skuStock : promotionProduct.getSkuStockList()) {
            if (productSkuId.equals(skuStock.getId())) {
                return skuStock;
            }
        }
        return null;
    }

    /**
     * 获取购物车中指定商品的数量
     */
    private int getCartItemCount(List<CartItem> itemList) {
        int count = 0;
        for (CartItem item : itemList) {
            count += item.getQuantity();
        }
        return count;
    }

    /**
     * 获取打折优惠的促销信息
     */
    private String getLadderPromotionMessage(ProductLadder ladder) {
        StringBuilder sb = new StringBuilder();
        sb.append("打折优惠：");
        sb.append("满");
        sb.append(ladder.getCount());
        sb.append("件，");
        sb.append("打");
        sb.append(ladder.getDiscount().multiply(new BigDecimal(10)));
        sb.append("折");
        return sb.toString();
    }

    /**
     * 获取满减促销消息
     */
    private String getFullReductionPromotionMessage(ProductFullReduction fullReduction) {
        StringBuilder sb = new StringBuilder();
        sb.append("满减优惠：");
        sb.append("满");
        sb.append(fullReduction.getFullPrice());
        sb.append("元，");
        sb.append("减");
        sb.append(fullReduction.getReducePrice());
        sb.append("元");
        return sb.toString();
    }


    /**
     * 对没满足优惠条件的商品进行处理
     */
    private void handleNoReduce(List<CartPromotionItem> cartPromotionItemList,List<CartItem> itemList,PromotionProduct promotionProduct){
        for (CartItem item : itemList) {
            CartPromotionItem cartPromotionItem = new CartPromotionItem();
            BeanUtils.copyProperties(item,cartPromotionItem);
            cartPromotionItem.setPromotionMessage("没有优惠");

            SkuStock skuStock = getOriginalPrice(promotionProduct, item.getProductSkuId());
            if(skuStock != null){
                cartPromotionItem.setRealStock(skuStock.getStock() - skuStock.getLockStock());
            }
            cartPromotionItem.setReduceAmount(BigDecimal.valueOf(0));
            cartPromotionItem.setIntegration(promotionProduct.getGiftPoint());
            cartPromotionItem.setGrowth(promotionProduct.getGiftGrowth());
            cartPromotionItemList.add(cartPromotionItem);
        }
    }


}
